package com.zktr.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

/**
 * 文件上传
 */

@WebServlet("/FileUp") // servlet3.0的规范，使用注解无需配置web.xml
@MultipartConfig // 加上该注解标识这个servlet支持文件上传，否则request.getParts()返回空，后台无法接收到文件
public class FileUp extends HttpServlet {
    private static final long serialVersionUID = 1L;
    /**
     * 后台接收文件方式一，该方式需要@MultipartConfig注解
     */
/*    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        String savePath = request.getServletContext().getRealPath("/myFiles");
        Collection<Part> files = request.getParts();

        for (Part file : files) {
            file.write(savePath + "/" + file.getName());
        }

    }*/

    /**
     * 后台接收文件方式二，该方式无需@MultipartConfig注解
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String savePath = request.getServletContext().getRealPath("/myFiles");
/*        DiskFileItemFactory factory = new DiskFileItemFactory(10*1024, new File("f:/temp"));
        ServletFileUpload upload = new ServletFileUpload(factory);*/
        //注意：通过设置文件头编码格式来解决文件名称中文乱码问题   
        System.out.println(savePath);
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8"); 
        
        try {
        	List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
        	System.out.println(items);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    System.out.println("savePath = " + savePath);
                     System.out.println(item.getName());
                    System.out.println(item.getFieldName());
                    item.write(new File(savePath+"/"+item.getFieldName()));
                    System.out.println(savePath + "/" + item.getFieldName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}